<template>
  <div class="document-parser">
    <div v-if="currentView === 'list'">
      <!-- 解析记录列表页面 -->
      <div class="header">
        <h1 class="page-title">文档解析</h1>
        <el-button type="primary" @click="showUploadDialog = true" class="upload-button">
          <el-icon class="el-icon">
            <Upload />
          </el-icon>
          上传文档
        </el-button>
      </div>
      <div class="content">
        <div class="quick-input-section">
          <div class="input-header">
            <h3>快速输入文字</h3>
            <div style="display: flex; gap: 8px;">
              <el-button type="info" @click="removeBlankLines" :disabled="parsing || !inputText.trim()" class="parse-button">
                <el-icon class="el-icon">
                  <Delete />
                </el-icon>
                去空行
              </el-button>
              <el-button type="success" @click="parseText" :loading="parsing" class="parse-button">
                <el-icon class="el-icon">
                  <Document />
                </el-icon>
                解析文字
              </el-button>
            </div>
          </div>
          <el-input
            v-model="inputText"
            type="textarea"
            :rows="6"
            placeholder="请输入要解析的文字内容..."
            class="text-input"
            :disabled="parsing"
          />
        </div>
        <div class="records-section">
          <div class="section-header">
            <h3>解析记录</h3>
            <el-button @click="refreshRecords" :loading="loading" class="refresh-button">
              <el-icon class="el-icon">
                <RefreshRight />
              </el-icon>
              刷新
            </el-button>
          </div>
          <el-empty 
            v-if="!loading && records.length === 0" 
            description="暂无解析记录"
            class="empty-state"
          >
            <el-button type="primary" @click="showUploadDialog = true">上传第一个文档</el-button>
          </el-empty>
          <div v-if="loading && records.length === 0" class="loading-container">
            <div class="loading-spinner">
              <div class="spinner-circle"></div>
              <div class="spinner-circle"></div>
              <div class="spinner-circle"></div>
            </div>
            <span class="loading-text">加载中...</span>
          </div>
          <div v-else class="records-list">
            <div v-for="record in records" 
                 :key="record.id" 
                 class="record-item"
                 :class="{ 'disabled-item': record.type === 2 || record.type === 'text' }"
                 @click="(record.type === 2 || record.type === 'text') ? null : enterDetail(record)">
              <div class="record-content">
                <div class="record-header">
                  <h4 class="record-title">{{ record.title || '未命名文档' }}</h4>
                  <div class="record-meta">
                    <span class="record-type" :class="record.type">
                      <el-icon>
                        <Document v-if="record.type === 'file' || record.type === 1" />
                        <EditPen v-else />
                      </el-icon>
                      {{ record.type === 'file' || record.type === 1 ? '整编中' : '待融合' }}
                    </span>
                  </div>
                </div>
                <div class="record-info">
                  <span class="segment-count">
                    <el-icon><Files /></el-icon>
                    {{ record.segmentCount || (record.segments?.length || 0) }} 个文段
                  </span>
                  <!-- <span class="file-size" v-if="record.fileSize">
                    <el-icon><Folder /></el-icon>
                    {{ formatFileSize(record.fileSize) }}
                  </span> -->
                </div>
                <!-- <p class="record-preview" v-if="record.preview">
                  {{ record.preview }}
                </p> -->
              </div>
              <div class="record-actions">
                <el-button 
                  v-if="record.type === 2 || record.type === 'text'"
                  type="primary"
                  link
                  @click.stop="handleFusion(record)"
                  class="action-button"
                >
                  <el-icon class="el-icon">
                    <EditPen />
                  </el-icon>
                  融合
                </el-button>
                <el-button 
                  type="danger" 
                  link
                  @click.stop="handleDeleteRecord(record)"
                  class="action-button"
                >
                  <el-icon class="el-icon">
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 上传文档对话框 -->
      <el-dialog
        v-model="showUploadDialog"
        title="上传文档"
        width="500px"
        :close-on-click-modal="false"
      >
        <div class="upload-content">
          <el-upload
            ref="uploadRef"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".txt,.doc,.docx,.pdf,.md"
            drag
            class="upload-area"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 txt、doc、docx、pdf、md 格式文件，文件大小不超过 10MB
              </div>
            </template>
          </el-upload>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showUploadDialog = false">取消</el-button>
            <el-button type="primary" @click="submitUpload" :loading="uploading">
              开始解析
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <DocumentDetailPage
      v-else-if="currentView === 'detail'"
      :record="currentRecord"
      @back="backToList"
      @edit-segment="enterEdit"
    />
    <SegmentEditor
      v-else-if="currentView === 'edit'"
      :segment-data="currentSegment"
      @back="backToDetail"
      @save="handleSegmentSave"
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMemoryData, saveDocument, deleteMemories } from '@/api/document'
import { 
  Upload, 
  Document, 
  EditPen, 
  Files, 
  Folder, 
  Delete, 
  RefreshRight,
  UploadFilled
} from '@element-plus/icons-vue'
import DocumentDetailPage from './views/DocumentDetailPage.vue'
import SegmentEditor from './views/SegmentEditor.vue'

export default {
  name: 'DocumentParser',
  components: {
    DocumentDetailPage,
    SegmentEditor
  },
  setup() {
    const inputText = ref('')
    const parsing = ref(false)
    const loading = ref(false)
    const uploading = ref(false)
    const showUploadDialog = ref(false)
    const records = ref([])
    const uploadRef = ref(null)
    let recordId = 100
    let segmentId = 1000
    // 页面切换相关
    const currentView = ref('list') // 'list' | 'detail' | 'edit'
    const currentRecord = ref(null)
    const currentSegment = ref(null)

    // 获取后端数据
    const fetchRecords = async () => {
      loading.value = true
      try {
        const res = await getMemoryData()
        if (res.data.success && Array.isArray(res.data.data)) {
          // 兼容后端数据结构
          records.value = res.data.data.map((item, idx) => ({
            ...item,
            id: idx + 1, // 若无id则用索引
            createTime: item.createTime || new Date(),
            preview: item.preview || (item.segments && item.segments[0]?.content?.slice(0, 30) + '...'),
            segments: (item.segments || []).map((seg, sidx) => ({
              ...seg,
              id: seg.id || sidx + 1,
              createTime: seg.createTime || new Date(),
            }))
          }))
        } else {
          records.value = []
        }
      } catch (e) {
        records.value = []
      }
      loading.value = false
    }
    const parseText = async () => {
      if (!inputText.value.trim()) {
        ElMessage.warning('请输入要解析的文字')
        return
      }
      // 弹窗输入标题
      let title = await new Promise((resolve) => {
        ElMessageBox.prompt('请输入文档标题', '文档标题', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入标题',
          inputValue: '',
        }).then(({ value }) => resolve(value)).catch(() => resolve(null))
      })
      if (!title) return
      parsing.value = true
      try {
        await saveDocument({ title, text: inputText.value })
        ElMessage.success('解析请求已提交')
        inputText.value = ''
        await fetchRecords()
      } catch (e) {
        ElMessage.error('解析失败')
      }
      parsing.value = false
    }
    const beforeUpload = (file) => {
      const isValidType = /\.(txt|doc|docx|pdf|md)$/.test(file.name.toLowerCase())
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isValidType) {
        ElMessage.error('只能上传 txt、doc、docx、pdf、md 格式的文件!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过 10MB!')
        return false
      }
      return true
    }
    const submitUpload = async () => {
      uploading.value = true
      await new Promise(r => setTimeout(r, 800))
      const segments = [1, 2, 3].map((_, idx) => ({
        id: ++segmentId,
        order: idx + 1,
        title: `文档段${idx + 1}`,
        content: `文档内容分段${idx + 1}`,
        updateTime: new Date(),
        readNum: 0
      }))
      records.value.unshift({
        id: ++recordId,
        title: `上传文档${recordId}`,
        type: 'file',
        createTime: new Date(),
        segmentCount: segments.length,
        fileSize: 1234567,
        preview: segments[0].content,
        segments
      })
      uploading.value = false
      showUploadDialog.value = false
      ElMessage.success('文档上传并解析成功')
    }
    // 页面切换
    const enterDetail = (record) => {
      currentRecord.value = record
      currentView.value = 'detail'
    }
    const enterEdit = (segment) => {
      currentSegment.value = segment
      currentView.value = 'edit'
    }
    const backToList = () => {
      currentView.value = 'list'
      currentRecord.value = null
    }
    const backToDetail = () => {
      currentView.value = 'detail'
      currentSegment.value = null
    }
    const handleSegmentSave = (updatedSegment) => {
      // 更新本地数据
      const segs = currentRecord.value.segments
      const idx = segs.findIndex(s => s.id === updatedSegment.id)
      if (idx !== -1) segs[idx] = { ...segs[idx], ...updatedSegment }
      // ElMessage.success('文段保存成功')
      backToDetail()
    }
    const handleDeleteRecord = async (record) => {
      await ElMessageBox.confirm('确定要删除这条解析记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      try {
        await deleteMemories([record.title])
        await fetchRecords()
        ElMessage.success('删除成功')
      } catch (e) {
        ElMessage.error('删除失败')
      }
    }
    const formatTime = (time) => new Date(time).toLocaleString()
    const formatFileSize = (bytes) => {
      if (!bytes) return ''
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    // 去空行功能
    const removeBlankLines = () => {
      if (!inputText.value) return
      inputText.value = inputText.value
        .split('\n')
        .filter(line => line.trim() !== '')
        .join('\n')
      ElMessage.success('空行已去除')
    }
    // 融合功能占位
    const handleFusion = (record) => {
      ElMessage.info('融合功能开发中')
    }
    onMounted(() => {
      fetchRecords()
    })
    return {
      inputText,
      parsing,
      loading,
      uploading,
      showUploadDialog,
      records,
      uploadRef,
      parseText,
      beforeUpload,
      submitUpload,
      enterDetail,
      enterEdit,
      backToList,
      backToDetail,
      handleSegmentSave,
      handleDeleteRecord,
      refreshRecords: fetchRecords,
      formatTime,
      formatFileSize,
      currentView,
      currentRecord,
      currentSegment,
      removeBlankLines,
      handleFusion
    }
  }
}
</script>

<style scoped>
.document-parser {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.upload-button {
  padding: 8px 20px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.upload-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.quick-input-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.input-header h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.parse-button {
  padding: 6px 16px;
  font-weight: 500;
}

.text-input {
  width: 100%;
}

.text-input :deep(.el-textarea__inner) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
  min-height: 120px;
}

.text-input :deep(.el-textarea__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 1px #409EFF;
}

.records-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.refresh-button {
  padding: 6px 12px;
  font-size: 0.9rem;
}

.empty-state {
  padding: 48px;
  text-align: center;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px;
}

.loading-spinner {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.spinner-circle {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #409EFF;
  animation: bounce 0.5s ease-in-out infinite;
}

.spinner-circle:nth-child(2) {
  animation-delay: 0.1s;
}

.spinner-circle:nth-child(3) {
  animation-delay: 0.2s;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.loading-text {
  color: #909399;
  font-size: 14px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.record-item:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.record-content {
  flex: 1;
  padding-right: 20px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.record-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.record-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.record-type {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.record-type.file {
  background-color: #e1f3d8;
  color: #67c23a;
}

.record-type.text {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.record-time {
  color: #909399;
  font-size: 12px;
}

.record-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}

.segment-count,
.file-size {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  font-size: 14px;
}

.record-preview {
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.record-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  font-size: 0.9rem;
}

.upload-content {
  padding: 20px 0;
}

.upload-area {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.upload-area :deep(.el-icon--upload) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-area :deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
}

.upload-area :deep(.el-upload__text em) {
  color: #409EFF;
  font-style: normal;
}

.upload-area :deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

@media (max-width: 768px) {
  .document-parser {
    padding: 0px;
  }

  .header {
    padding: 12px 16px;
    margin-bottom: 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .page-title {
    font-size: 1.2rem;
    text-align: center;
  }

  .quick-input-section,
  .records-section {
    padding: 16px;
  }

  .input-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .record-item {
    padding: 16px;
  }

  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .record-meta {
    gap: 8px;
  }

  .record-info {
    gap: 12px;
  }

  .action-button span {
    display: none;
  }

  .upload-area :deep(.el-upload-dragger) {
    height: 150px;
  }

  .upload-area :deep(.el-icon--upload) {
    font-size: 36px;
  }
}

.disabled-item {
  cursor: not-allowed;
  opacity: 0.7;
  pointer-events: auto;
}
</style> 